// pages/addCart/addCart.js
const app = getApp();
import httpsUtils from '../../utils/https.js';
import calcUtil from '../../utils/calcUtil.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hiddenmodalput: true,
    goodsData: {},//商品数据
    storesList: [],//库存信息
    storesLength: 0,
    count: 0,
    totalMoney: 0.00,//总计
    price: 0.00,//单价

    goodsType: 1, //默认1表示正常订单 3表示抢购订单
    cheapPrice: 0.00, //优惠价格
  },
  /*事件函数*/
  /* 点击减号*/
  minusCount: function (e, item) {
    var _data = this.data.storesList;//重新获取列表
    var _leftid = e.currentTarget.dataset.leftid;
    for (let obj of _data) {
      if (obj.id == _leftid && obj.num > 0) {
        obj.num = obj.num - 1;
      }
    }

    this.setData({
      storesList: _data,
    })
    //计算金额
    this.calcMoney();
  },
  /* 点击加号 */
  addCount: function (e, item) {
    var _data = this.data.storesList;//重新获取列表
    var _leftid = e.currentTarget.dataset.leftid;
    for (let obj of _data) {
      if (obj.id == _leftid && obj.num < obj.leftNum) {
        obj.num = obj.num + 1;
      }
    }
    this.setData({
      storesList: _data,
    })
    //计算金额
    this.calcMoney();
  },
  /* 输入框事件 */
  bindManual: function (e) {
    var _data = this.data.storesList;//重新获取列表
    var _changeNum = Math.floor(e.detail.value);
    var _leftid = e.currentTarget.dataset.leftid;
    var _originNum = 0;

    for (let obj of _data) {
      if (obj.id == _leftid && _changeNum >= 0 && _changeNum <= obj.leftNum) {
        obj.num = _changeNum;
      }
    }

    this.setData({
      storesList: _data,
    })

    //计算金额
    this.calcMoney();
  },
  /**
   * 计算金额
   */
  calcMoney: function () {
    var _data = this.data.storesList;
    var goodsData = this.data.goodsData;
    var price = this.data.price;

    var count = 0;
    var totalMoney = 0.00;
    for (let obj of _data) {
      count += obj.num;
    }

    if (count >= goodsData.packNumber) {
      totalMoney = calcUtil.mul(count, goodsData.packPrice).toFixed(2);
      price = goodsData.packPrice.toFixed(2);
    } else {
      totalMoney = calcUtil.mul(count, goodsData.tradePrice).toFixed(2);
      price = goodsData.tradePrice.toFixed(2);
    }

    this.setData({
      count: count,
      totalMoney: totalMoney,
      price: price
    })

  },
  /**
   * 确认添加
   */
  confirmAdd: function () {
    var that = this;
    var _data = this.data.storesList;
    var price = this.data.price;
    var _param = [];
    var goodsType = parseInt(this.data.goodsType);

    for (let obj of _data) {
      if (obj.num > 0) {
        _param.push({ id: obj.id, saleNum: obj.num, packRate: price, zbDirectSeedingId: '', goodsType: goodsType })
      }
    }
    httpsUtils.postData({
      _url: app.globalData._url + '/goodsCar/add1',
      data: { 'myStocks': JSON.stringify(_param) },
    }, function (json) {
      if (json.success) {
        //提示
        wx.showModal({
          title: '添加成功',
          content: '',
          cancelText: '随便逛逛',
          confirmText: '立即结算',
          success: function (res) {
            if (res.confirm) {
              wx.switchTab({
                url: '../cart/cart'
              })
            } else if (res.cancel) {
              wx.navigateBack({
                delta: 1,
              })
            }
          }
        })
      } else if (json.success == false && json.code == 'OVERTIME') {
        wx.navigateTo({
          url: '../wxLogin/wxLogin?type=4&isTab=false',
        })
      } else {
        wx.showModal({
          title: '提示',
          content: json.msg,
          showCancel: false
        })
      }
    })
  },

  /*  加入购物车后弹框   */
  addSuccess: function () {
    var that = this;
    var count = that.data.count;
    var goodsData = that.data.goodsData;
    if (count < goodsData.tradeNumber) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '起批数量大于或等于' + goodsData.tradeNumber + '件以上才能加入购物车',
      })
      return;
    }

    //确认添加
    that.confirmAdd();

  },
  /**
   * 初始化参数
   */
  initData: function (options) {
    var that = this;
    if (options.goodsType != undefined) {
      that.setData({
        goodsType: options.goodsType,
        cheapPrice: options.cheapPrice,
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中...',
      mask: true,
    })
    var that = this;
    var goodsType = options.goodsType;
    var cheapPrice = options.cheapPrice;
    //初始化参数
    that.initData(options);

    httpsUtils.getData({
      _url: app.globalData._url + '/goods/selectColorAndSizeByGoodsId?goodsId=' + options.id,
      data: {},
    }, function (json) {
      if (json.data && json.success) {
        var storesList = [];
        for (let obj of json.data.list) {
          var num = 0;
          if (obj.myStock != null) {
            num = obj.myStock.saleNum
          }
          storesList.push({
            id: obj.id,
            colourName: obj.colour.colourName,
            sizeName: obj.size.sizeName,
            leftNum: obj.leftNum,
            num: num
          })
        }

        var goodsData = json.data.goods;
        cheapPrice = parseFloat(cheapPrice);
        var price = json.data.goods.tradePrice;
        if (goodsType == 3) {
          goodsData.tradePrice = cheapPrice;
          goodsData.packPrice = cheapPrice;
          price = cheapPrice;
        }

        that.setData({
          goodsData: goodsData,
          storesList: storesList,
          storesLength: storesList.length,
          price: price
        })
        //计算金额
        that.calcMoney();
      }
      wx.hideLoading();
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

})